package com.demo.pong.controller


import com.demo.pong.service.PongService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.server.ResponseStatusException
import reactor.core.publisher.Mono
import spock.lang.Specification

/**
 * @author Jofo
 */
class PongControllerTest extends Specification {

    def pongService = Mock(PongService)
    def controller = new PongController(pongService: pongService)

    def "should return OK response with message"() {
        given:
        def msg = "Hello"
        def traceId = "1234567890"
        def expectedResponse = "Pong: Hello"

        when:
        def result = controller.pongMsg(msg, traceId).block()

        then:
        1 * pongService.respond(msg, traceId) >> Mono.just(expectedResponse)
        result == ResponseEntity.ok(expectedResponse)
    }

    def "should handle too many requests exception"() {
        given:
        def msg = "Hello"
        def traceId = "1234567890"
        def responseStatusException = new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS, "Too many requests")

        when:
        def result = controller.pongMsg(msg, traceId).block()

        then:
        1 * pongService.respond(msg, traceId) >> Mono.error(responseStatusException)
        result.getStatusCode().value() == HttpStatus.TOO_MANY_REQUESTS.value()
    }

    def "should handle other exceptions"() {
        given:
        def msg = "Hello"
        def traceId = "1234567890"
        def exception = new RuntimeException("Something went wrong")

        when:
        def result = controller.pongMsg(msg, traceId).block()

        then:
        1 * pongService.respond(msg, traceId) >> Mono.error(exception)
        result == ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
            .body("Error: RuntimeException: Something went wrong, traceId: 1234567890")
    }
}
